<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加分类区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCartDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 商品分类列表区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-show="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i
            class="el-icon-error"
            v-show="scope.row.cat_deleted === true"
            style="color: red"
          ></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else> 三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot-scope="scope" slot="opt">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="getCartInfoById(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCartById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCartDialogVisible"
      width="50%"
      @close="addCartDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addCartForm"
        :rules="addCartFormRules"
        ref="addCartFromRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCartForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectKeys"
            :options="parentCateList"
            :props="casaderProps"
            @change="parentCartChange"
            clearable
          ></el-cascader
        ></el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCartDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCart">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="修改分类"
      width="50%"
      :visible.sync="editCartDialogVisible"
      @close="editCartDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="editCartForm"
        :rules="editCartFormRules"
        ref="editCartFromRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCartForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCartDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCart">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      // 商品分类数据列表
      cateList: [],
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 总数据条数
      total: 0,
      // 为table指定列
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 表示当前列定义为模板列
          type: "template",
          // 表示当前列使用模板名称
          template: "isOk",
        },
        {
          label: "排序",
          // 表示当前列定义为模板列
          type: "template",
          // 表示当前列使用模板名称
          template: "order",
        },
        {
          label: "操作",
          // 表示当前列定义为模板列
          type: "template",
          // 表示当前列使用模板名称
          template: "opt",
        },
      ],
      // 控制添加分类是否可见
      addCartDialogVisible: false,
      // 添加商品分类的表单
      addCartForm: {
        // 添加分类的名称
        cat_name: "",
        // 父级分类的id
        cat_pid: 0,
        // 添加分类的等级,默认一级
        cat_level: 0,
      },
      // 添加商品分类的表单验证规则
      addCartFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 父级分类列表
      parentCateList: [],
      // 指定级联选择器的配置对象
      casaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      // 选中父级分类的Id数组
      selectKeys: [],
      // 控制编辑对话框的显示与否
      editCartDialogVisible: false,
      // 编辑分类的表单
      editCartForm: {
        cat_name: "",
        cat_id: 0,
      },
      // 编辑分类的校验规则
      editCartFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      console.log(res);
      this.cateList = res.data.result;
      this.total = res.data.total;
    },

    // 监听pagesize的改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },

    // 监听pagenum的改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },

    // 显示添加分类对话框
    showAddCartDialog() {
      this.getParentCartList();
      this.addCartDialogVisible = true;
    },

    // 监听添加分类对话框关闭
    addCartDialogClosed() {
      this.$refs.addCartFromRef.resetFields();
      // 情况级联选择器
      this.selectKeys = [];
      this.addCartForm.cat_pid = 0;
      this.addCartForm.cat_level = 0;
    },

    // 点击确定，新增分类
    addCart() {
      this.$refs.addCartFromRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCartForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");
        this.$message.success("添加分类成功");
        this.getCateList();
        this.addCartDialogVisible = false;
      });
    },

    // 获取父级商品分类列表
    async getParentCartList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类列表失败");
      this.parentCateList = res.data;
    },

    //选中级联选择器中的值
    parentCartChange() {
      if (this.selectKeys.length > 0) {
        this.addCartForm.cat_pid = this.selectKeys[this.selectKeys.length - 1];
        this.addCartForm.cat_level = this.selectKeys.length;
        return;
      } else {
        this.addCartForm.cat_level = 0;
        this.addCartForm.cat_pid = 0;
      }
    },

    // 监听编辑分类对话框的关闭
    editCartDialogClosed() {
      this.$refs.editCartFromRef.resetFields();
    },

    // 点击编辑，根据分类id获取分类信息
    async getCartInfoById(id) {
      const { data: res } = await this.$http.get(`categories/${id}`);
      if (res.meta.status !== 200)
        return this.$message.error("获取分类信息失败");
      this.editCartForm.cat_name = res.data.cat_name;
      this.editCartForm.cat_id = res.data.cat_id;
      this.editCartDialogVisible = true;
    },

    // 点击确定，发送请求更改分类名称
    async editCart() {
      this.$refs.editCartFromRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.editCartForm.cat_id}`,
          { cat_name: this.editCartForm.cat_name }
        );
        if (res.meta.status !== 200) return this.$message.error("修改分类失败");
        this.$message.success("修改分类成功");
        this.getCateList();
        this.editCartDialogVisible = false;
      });
    },

    // 点击删除，根据分类id删除
    async removeCartById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);

      //用户点击确认，confirmResult值为confirm
      if (confirmResult !== "confirm") return this.$message.info("已取消删除");

      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除分类失败");
      this.$message.success("删除分类成功");
      this.getCateList();
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 15px;
}

.el-cascader {
  width: 100%;
}
</style>